<template>
  <view class="wallet-wrap">
    <swiper
      class="swiper-box"
      :current="currentIndex"
      @change="handleSwiperChange"
      previous-margin="12px"
      next-margin="32px"
    >
      <swiper-item
        class="swiper-item"
        v-for="(item, index) in computedStatusList"
        :key="index"
      >
        <view class="head_box u-flex u-row-center u-col-center">
          <view
            class="card-box"
            :style="{
              background: 'url(' + item.bgColor + ') no-repeat center center',
            }"
          >
            <view class="card-box_title">{{ item.name }}</view>
            <view
              style="
                display: flex;
                align-items: flex-start;
                justify-content: space-between;
              "
            >
              <view>
                <view class="card-head u-flex u-col-center">
                  <view class="card-title u-m-r-10"
                    >可提现总金额（元）
                    <image
                      v-if="showMoney"
                      @tap="showMoney = !showMoney"
                      src="../../static/images/eyes_icon.png" />
                    <image
                      v-else
                      @tap="showMoney = !showMoney"
                      src="../../static/images/eyes_close_icon.png"
                  /></view>
                  <!-- <view
                   
                    class="u-iconfont"
                    :class="showMoney ? 'uicon-eye' : 'uicon-eye-off'"
                    style="color: #fff; font-size: 38rpx; font-weight: bold"
                  >

                </view> -->
                </view>
                <view class="money-num u-p-t-20 u-p-b-10">{{
                  showMoney ? item.amount : "*****"
                }}</view>
                <!-- <view>当天总收益 {{ item.amount }}</view> -->
              </view>
              <view>
                <button
                  class="u-reset-button withdraw-btn"
                  :style="{ color: item.color }"
                  @tap="taps"
                >
                  提现
                </button>
                <view style="height: 32rpx"></view>
                <button
				v-if="currentIndex !== 1"
                  class="u-reset-button withdraw-btn"
                  :style="{ color: item.color }"
                  @tap="() => taps('transfer')"
                >
                  划转
                </button>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>
    <i-date-timer @confirm="confirmTime"></i-date-timer>

    <EquipmentSales
      :cardList="cardList"
      @handleTab="handleTab"
      :allAmount="allAmount"
    ></EquipmentSales>
    <view class="banner-wrap">
      <homeSwiper :list="bannerList"></homeSwiper>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import useStore from "../../stores/index";
import EquipmentSales from "./components/equipmentSales.vue";
import { formatDate } from "../../utils/common";
import {
  equipmentSalesList,
  WithdrawablePriceList,
  channelAgentList,
} from "./helps.ts";
import { getAd, getUserIncomeStatistics, getUserAccountVo } from "../../api";
import homeSwiper from "../index/components/homeSwiper.vue";

// 类型定义
interface StatusItem {
  name: string;
  value: string;
  amount: number;
  bgColor: string;
  color: string;
  price?: number;
}

interface FormData {
  startDate: string;
  endDate: string;
  statisticsType: number;
}

interface UserInfo {
  amount: number;
  merchantAmount: number;
  chargingAmount: number;
  channelAmount?: number;
  totalAmount?: number;
}

// Store
const store = useStore();
const userInfo: any = computed(() => store.userInfo);
const isLogin = computed(() => !!store.userInfo?.userId);
const allAmount = ref<string|number>("0");
const bannerList = ref<any>([]);

// Refs
const currentIndex = ref(0);
const isEmpty = ref(false);
const showMoney = ref(true);
const showCalendar = ref(false);
const selDateText = ref("");
const walletLog = ref<any[]>([]);
const propsDate = ref("");
const incomeMoney = ref("");
const expendMoney = ref("");
const loadStatus = ref("loadmore");
const currentPage = ref(1);
const lastPage = ref(1);
const cardList = ref<any>([]);

// 数据
const statusList = ref<any[]>([
  {
    name: "设备销售",
    value: "1",
    amount: 0,
    selectType: 0,
    bgColor: "../../static/images/wallet/sbxs_bg.png",
    color: "#8c97e0",
    allAmount: 0,
  },
  {
    name: "充电流水",
    value: "2",
    amount: 0,
    selectType: 1,
    bgColor: "../../static/images/wallet/cdls_bg.png",
    color: "#f6c543",
    allAmount: 0,
  },
  {
    name: "渠道收益",
    value: "3",
    amount: 0,
    selectType: 7,
    bgColor: "../../static/images/wallet/qdsy_bg.png",
    color: "#afd559",
    allAmount: 0,
  },
]);

const formData = ref<FormData>({
  startDate: "",
  endDate: "",
  statisticsType: 0,
});

// 计算属性
const computedStatusList = computed(() => {
  return statusList.value.map((item) => {
    if (item.value === "1") {
      return { ...item, price: userInfo.value.totalAmount };
    } else if (item.value === "2") {
      return { ...item, price: userInfo.value.chargingAmount };
    } else if (item.value === "3") {
      return { ...item, price: userInfo.value.merchantAmount };
    }
    return item;
  });
});

const getBanner = async () => {
  const { data } = await getAd("0");
  bannerList.value = data;
};

const getUserAccountVoData = async () => {
 try {
  const { data } = await getUserAccountVo();
  statusList.value.forEach((item) => {
    if (item.value === "1") {
      item.allAmount = Number((data.merchantAmount || 0) + (data.amount || 0)).toFixed(2);
      item.amount = Number(
        (
          Number(userInfo.value.amount) + Number(userInfo.value.merchantAmount)
        ).toFixed(2)
      );
    } else if (item.value === "2") {
      item.allAmount = data.chargingAmount;
      item.amount = Number(Number(userInfo.value.chargingAmount).toFixed(2));
    } else if (item.value === "3") {
      item.allAmount = data.channelAmount;
      item.amount = Number(
        Number(userInfo.value.channelAmount || 0).toFixed(2)
      );
    }
  });
  // 根据当前选中的索引设置 allAmount
  const currentItem = computedStatusList.value[currentIndex.value];
  allAmount.value = currentItem ? currentItem.allAmount : "0";
  
 } catch (error) {
  console.log(error);
 }
};

// 方法

const getUserIncomeStatisticsData = async (type: number) => {
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });

  const { data } = await getUserIncomeStatistics(formData.value);
  if (currentIndex.value === 0) {
    equipmentSalesList.forEach((item: any) => {
      item.value = data[item.key];
    });
    cardList.value = [...equipmentSalesList];
  } else if (type === 1) {
    WithdrawablePriceList.forEach((item: any) => {
      item.value = data[item.key];
    });
    cardList.value = [...WithdrawablePriceList];
  } else {
    channelAgentList.forEach((item: any) => {
      item.value = data[item.key];
    });
    cardList.value = [...channelAgentList];
  }
  uni.hideLoading();
};

const handleSwiperChange = (e: any) => {
  currentIndex.value = e.detail.current;
  formData.value.statisticsType = currentIndex.value;
  getUserIncomeStatisticsData(currentIndex.value);
  allAmount.value = computedStatusList.value[currentIndex.value].allAmount;
};

const handleTab = (value: any) => {
  uni.navigateTo({
    url: `/pages/wallet/specification?amountType=${
      value.typeCode || 0
    }&startDate=${formData.value.startDate}&endDate=${
      formData.value.endDate
    }&cardType=${currentIndex.value}`,
  });
};

const confirmTime = (e: { startDate: string; endDate: string }) => {
  console.log(e);
  formData.value.startDate = e.startDate + " 00:00:00";
  formData.value.endDate = e.endDate + " 23:59:59";
  getUserIncomeStatisticsData(currentIndex.value);
};

const taps = (type: string = "") => {
  const selectType = computedStatusList.value[currentIndex.value].selectType;

  if (type === "transfer") {
    uni.navigateTo({
      url: `/pages/views/transferPrice?selectType=${selectType}`,
    });
    return;
  }
  uni.navigateTo({
    url: `/pages/withdrawal/index?selectType=${  selectType == 7 ? 3 : selectType}`,
  });
};

// 生命周期
onLoad(() => {
  formData.value.startDate = "2024-05-01 00:00:00";
  formData.value.endDate = formatDate(
    new Date().getTime(),
    "YYYY-MM-DD 23:59:59"
  );
  getBanner();
});

onShow(async () => {
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });

  await store.setUserInfo();
  getUserIncomeStatisticsData(currentIndex.value);
  getUserAccountVoData();

});
</script>

<style lang="scss" scoped>
.wallet-wrap {
  overflow: hidden;
}
.swiper-box {
  height: 342rpx;
  .swiper-item {
    width: 100%;
    height: 100%;
  }
}

.head_box {
  width: calc(100% - 24rpx);
  padding: 30rpx 0;

  .card-box {
    width: 100%;
    height: 280rpx;
    padding: 18rpx 32rpx;
    border-radius: 12rpx;
    overflow: hidden;
    position: relative;
    box-sizing: border-box;
    background-size: cover;
    background-position: center;
    overflow: hidden;

    .card-box_title {
      font-weight: 500;
      font-size: 32rpx;
      text-align: center;
      margin-bottom: 24rpx;
      color: #fff;
    }

    .card-head {
      color: #fff;
      font-size: 30rpx;
      .card-title  {
        @include flexR;
        image {
          width: 32rpx;
          height: 32rpx;
        }
      }
    }

    .money-num {
      font-size: 48rpx;
      font-weight: 500;
      color: #ffffff;
    }

    .reduce-num {
      font-size: 26rpx;
      font-weight: 400;
      color: #ffffff;
    }

    .withdraw-btn {
      width: 120rpx;
      height: 48rpx;
      line-height: 48rpx;
      background: #ffffff;
      border-radius: 30px;
      font-size: 24rpx;
      font-weight: 500;
      color: #5848c4;
    }

    .topup-btn {
      width: 120rpx;
      height: 60rpx;
      line-height: 60rpx;
      border-radius: 30px;
      font-size: 24rpx;
      font-weight: 500;
      color: #fff;
      border: 1px solid #fff;
      position: absolute;
      right: 180rpx;
      top: 40rpx;
    }
  }
}
.banner-wrap {
  margin-top: 24rpx;
  padding: 0 24rpx;
  box-sizing: border-box;
}
</style>
